import { isArray } from ".store/@vue+shared@3.3.10/node_modules/@vue/shared";
import { defineComponent } from "vue";
import styles from "./SearchForm.module.less";

export default defineComponent({
  props: {
    config: {
      type: Array,
    }
  },
  setup(props, { expose }) {
    const ItemForm = (itemFormProps: any) => {
      switch (itemFormProps.item.type) {
        case "input":
          return <a-input allowClear={true} v-model:value={itemFormProps.item.value} placeholder="请输入" {...itemFormProps.item.attrs} />;
        case "select":
          return <a-select
            allowClear={true}
            options={itemFormProps.item.datas}
            style={{ minWidth: "200px" }}
            placeholder="全部"
            v-model:value={itemFormProps.item.value}
            {...itemFormProps.item.attrs}
          ></a-select>;
        case "rangePicker":
          return <a-range-picker v-model:value={itemFormProps.item.value} {...itemFormProps.item.attrs} />;
        case "custom":
          return itemFormProps.item.el?.(props.config, itemFormProps.index);
        default:
          return <div></div>
      }
    }
    const getFormData = () => {
      let formData = {};
      props.config?.forEach((x: any) => {
        if (x.type === "input") {
          x.value && (formData[x.key] = x.value);
        } else if (x.type === "select") {
          x.value && (formData[x.key] = x.value);
        } else if (x.type === "custom") {
          x.value && (formData[x.key] = x.value);
        } else if (x.type === "rangePicker") {
          const sDate = x.value[0] ? (x.value[0].$y + '-' + String(x.value[0].$M + 1).padStart(2, '0') + '-' + String(x.value[0].$D).padStart(2, '0')) : '';
          const eDate = x.value[1] ? (x.value[1].$y + '-' + String(x.value[1].$M + 1).padStart(2, '0') + '-' + String(x.value[1].$D).padStart(2, '0')) : '';
          if (isArray((x.key))) {
            sDate && (formData[x.key[0]] = sDate);
            eDate && (formData[x.key[1]] = eDate);
          } else {
            (sDate && eDate) && (formData[x.key] = [sDate, eDate]);
          }
        }
      })
      return formData;
    }
    expose({
      getFormData,
    })
    return () => (
      <>
        {
          (props.config && props.config.length > 0) && <div class={styles.searchForm}>
            <a-space wrap>
              {
                props.config.map((item: any, index: number) => (
                  <div class={styles.searchFormItem}>
                    <div class={styles.label}>{item.label}</div>
                    <ItemForm item={item} index={index} />
                  </div>
                ))
              }
            </a-space>
          </div>
        }
      </>
    )
  }
})